package com.ruoyi.system.interAttr.attr;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.UUIDGenerator;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.interAttr.domain.GamesRes;
import com.ruoyi.system.interAttr.domain.InterAttrRes;
import com.ruoyi.system.interAttr.domain.InterServerRes;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.outto.dto.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 起飞属性匹配
 *
 * @author ruoyi
 * @data 2024/7/3
 * @apiNote
 */
@Service
@Slf4j
public class NEW5173Attr implements AdapterAttr {
    static String APPID = "sGO2wUx7j1t8tBQOuYeYgLN7";
    static String APPSECRET = "OvRDE52zhiZtvWje";
    static String URL = "http://gu.5173.com:9188";

    public static void main(String[] args) {
        String url = "http://gu.5173.com:9188/api/game/getGameAccountData?game_id="+43;
        Map<String, String> header = getHeader("XyfJp091RVjAGAAMcHxjLSc3", "AKWO7FzKfNFEJMf4");
        Map<String, String> action = new HashMap<>();
        String response = HttpUtil.doGet(url, action, header);
        System.out.println(response);
//        SalePartner salePartner = JSONObject.parseObject("{\"channelType\":1,\"closeTime\":1724515200000,\"createId\":1,\"createName\":\"若依\",\"createTime\":1721897538000,\"fiveOther\":\"18240760493\",\"fourOther\":\"18240760493\",\"gameId\":\"29\",\"id\":51,\"interfaceUserId\":118,\"interfaceUserName\":\"5173\",\"isMonth\":1,\"merchantUserId\":14,\"merchantUserName\":\"涛哥的店铺\",\"name\":\"涛哥的店铺_5173\",\"other\":\"6QDZwFID0F1sYiosShxP0r9d\",\"params\":{},\"pricePushType\":1,\"saleKey\":\"nqWMTHdv7OEGvU6L\",\"saleName\":\"14_5173\",\"seleep\":1,\"status\":\"1\",\"tenantId\":14,\"threeOther\":\"18240760493\",\"twoOther\":\"潘壮壮\",\"valueAddedServiceId\":98}", SalePartner.class);
//        List<InterServerRes> resultList = new ArrayList<>();
//        String url = "http://gu.5173.com:9188/api/game/dict?game_id=248";
//        Map<String, String> header = getHeader(salePartner.getOther(), salePartner.getSaleKey());
//        Map<String, String> action = new HashMap<>();
//        String response = HttpUtil.doGet(url, action, header);
//        System.err.println(response);
//        JSONObject data = JSONObject.parseObject(response).getJSONObject("data");
//
//        for (String k : data.keySet()) {
//            JSONObject valueJson = data.getJSONObject(k);
//
//            InterServerRes res = new InterServerRes();
//            res.setId(k);
//            res.setName(k);
//            List<InterServerRes> valueList = new ArrayList<>();
//            InterServerRes children = new InterServerRes();
//
//            for (String key : valueJson.keySet()) {
//                children  =new InterServerRes();
//                children.setName(key);
//                children.setId(valueJson.getString(key));
//                valueList.add(children);
//            }
//            res.setInterServerRes(valueList);
//            resultList.add(res);
//        }
//        System.out.println(JSONObject.toJSONString(resultList));
    }

    /**
     * 获取游戏列表
     *
     * @return
     */
    @Override
    public List<GamesRes> getGames(SalePartner salePartner) {
        List<GamesRes> gamesResList = new ArrayList<>();
        String url = "http://gu.5173.com:9188/api/games?page=1&page_size=999";
        Map<String, String> header = getHeader(salePartner.getSaleKey(), salePartner.getOther());
        Map<String, String> action = new HashMap<>();
        String response = HttpUtil.doGet(url, action, header);
        String data1 = JSONObject.parseObject(response).getString("data");
        String items = JSONObject.parseObject(data1).getString("items");
        List<JSONObject> itemsList = JSONObject.parseArray(items, JSONObject.class);
        for (JSONObject data : itemsList) {
            GamesRes res = new GamesRes();
            res.setId(data.getString("id"));
            res.setGameName(data.getString("name"));
            gamesResList.add(res);
        }
        return gamesResList;
    }

    /**
     * 获取游戏区服列表
     *
     * @return
     */
    @Override
    public List<InterServerRes> getServer(String gameId, SalePartner salePartner) {

        List<InterServerRes> resultList = new ArrayList<>();
        String url = "http://gu.5173.com:9188/api/game/dict?game_id="+gameId;
        Map<String, String> header = getHeader(salePartner.getSaleKey(), salePartner.getOther());
        Map<String, String> action = new HashMap<>();
        String response = HttpUtil.doGet(url, action, header);
        System.err.println(response);
        JSONObject data = JSONObject.parseObject(response).getJSONObject("data");

        for (String k : data.keySet()) {
            JSONObject valueJson = data.getJSONObject(k);

            InterServerRes res = new InterServerRes();
            res.setId(k);
            res.setName(k);
            List<InterServerRes> valueList = new ArrayList<>();
            InterServerRes children = new InterServerRes();

            for (String key : valueJson.keySet()) {
                children  =new InterServerRes();
                children.setUuid(UUIDGenerator.generateUuid6());
                children.setName(key);
                children.setId(valueJson.getString(key));
                valueList.add(children);
            }
            res.setInterServerRes(valueList);
            resultList.add(res);
        }
        return resultList;
    }

    /**
     * 获取游戏属性列表
     *
     * @return
     */
    @Override
    public List<InterAttrRes> getPropety(String gameId, String type, SalePartner salePartner) {
        String url = "http://gu.5173.com:9188/api/game/getGameAccountData?game_id="+gameId;
        Map<String, String> header = getHeader(salePartner.getSaleKey(), salePartner.getOther());
        Map<String, String> action = new HashMap<>();
        String response = HttpUtil.doGet(url, action, header);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String datas = jsonObject.getString("data");
        String items = JSONObject.parseObject(datas).getString("items");
        List<JSONObject> data = JSONObject.parseArray(items, JSONObject.class);
//        List<JSONObject> collect = new ArrayList<>();
//        if (Objects.equals("1",type)){
//            collect = data.stream().filter(d -> d.getString("type").equals("select")).collect(Collectors.toList());
//        }else if  (Objects.equals("2",type)){
//            collect = data.stream().filter(d -> d.getString("type").equals("checkbox")).collect(Collectors.toList());
//        }else if (Objects.equals("3",type)){
//            collect = data.stream().filter(d -> d.getString("type").equals("text")).collect(Collectors.toList());
//        }
        List<InterAttrRes> resultList = new ArrayList<>();
        for (JSONObject datum : data) {

            InterAttrRes res = new InterAttrRes();
            if (StringUtils.equals(type, "1")) {
                if (StringUtils.equals(datum.getString("type"), "select")) {
                    res.setId(datum.getString("id"));
                    res.setName(datum.getString("keyname"));
                    res.setRequired(datum.getBoolean("must"));
                    String values = datum.getString("value");
                    List<InterAttrRes> arrayList = new ArrayList<>();
                    List<String> list = Arrays.asList(values.split(","));
                    for (String s : list) {
                        InterAttrRes res1 = new InterAttrRes();
                        res1.setId(s);
                        res1.setName(s);
                        res1.setRequired(false);
                        arrayList.add(res1);
                    }
                    res.setInterServerRes(arrayList);
                    resultList.add(res);
                }
            } else if (StringUtils.equals(type, "2")) {
                // 针对原神 DNF 有多重属性的筛选项
                if (StringUtils.equals(datum.getString("type"), "checkbox")) {
                    if (CollectionUtils.isNotEmpty(datum.getJSONArray("children"))){
                        List<JSONObject> array = JSONObject.parseArray(datum.getString("children"), JSONObject.class);
                        for (JSONObject jsonObject2 : array) {
                            res.setId(jsonObject2.getString("id"));
                            res.setName(jsonObject2.getString("keyname"));
                            res.setRequired(jsonObject2.getBoolean("must"));
                            String values = jsonObject2.getString("value");
                            List<InterAttrRes> arrayList = new ArrayList<>();
                            //  子选项 会有   ;  , 两种分割方式
                            List<String> sList = Arrays.asList(values.split(";"));
                            for (String ss : sList) {
                                List<String> list = Arrays.asList(ss.split(","));
                                for (String s : list) {
                                    InterAttrRes res1 = new InterAttrRes();
                                    res1.setId(s);
                                    res1.setName(s);
                                    res1.setRequired(false);
                                    arrayList.add(res1);
                                }
                            }
                            res.setInterServerRes(arrayList);
                            resultList.add(res);

                        }
                    }else{
                        res.setId(datum.getString("id"));
                        res.setName(datum.getString("keyname"));
                        res.setRequired(datum.getBoolean("must"));
                        String values = datum.getString("value");
                        List<InterAttrRes> arrayList = new ArrayList<>();
                        List<String> list = Arrays.asList(values.split(","));
                        for (String s : list) {
                            InterAttrRes res1 = new InterAttrRes();
                            res1.setId(s);
                            res1.setName(s);
                            res1.setRequired(false);
                            arrayList.add(res1);
                        }
                        res.setInterServerRes(arrayList);
                        resultList.add(res);
                    }
                }
            } else if (StringUtils.equals(type, "3")) {
                if (StringUtils.equals(datum.getString("type"), "text")) {
                    res.setId(datum.getString("id"));
                    res.setName(datum.getString("keyname"));
                    res.setRequired(datum.getBoolean("must"));
                    resultList.add(res);
                }
            }
        }
        return resultList;
    }

    public static Map<String, String> getHeader(String appId, String appSecret) {

        String curTime = String.valueOf(Instant.now().getEpochSecond());

        Map<String, String> params = new HashMap<>();
        params.put("Appid", appId);
        params.put("CurTime", curTime);

        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        StringBuilder signMessage = new StringBuilder();
        for (String key : keys) {
            try {
                if (signMessage.length() > 0) {
                    signMessage.append("&");
                }
                signMessage.append(URLEncoder.encode(key, "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(params.get(key), "UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        String sign = generateSignature(signMessage.toString(), appSecret);
        params.put("Sign", sign);
        return params;
    }

    public static String generateSignature(String message, String secretKey) {
        try {
            Mac sha256Hmac = Mac.getInstance("HmacSHA256");
            SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256Hmac.init(secretKeySpec);
            byte[] hash = sha256Hmac.doFinal(message.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hash);
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate HMAC : " + e.getMessage());
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }


}
